<template>
    <!--    731width-->
    <div style="width: 1010px;background-color: pink;margin: 0 auto">
        <el-card>
            <!--        标题-->
            <div class="title" style="text-align: center;font-size: 28px;font-weight: 500">{{blog.title}}</div>
            <div style="text-align: center;margin-top: 5px"><i class="el-icon-watch"></i><span style="font-size: 12px">{{blog.formatSimply}}</span><i
                    class="el-icon-view" style="margin-left: 5px"></i><span
                    style="font-size: 12px">{{blog.views}}</span> <i class="iconfont icon-dianzan"></i>
                <span style="font-size: 12px">{{blog.thumbs}}</span> <i class="el-icon-edit"
                                                                        style="margin-left: 5px"> </i><span
                        style="font-size: 12px">字数≈{{blog.count}}</span>
                <i class="el-icon-time" style="margin-left: 8px"><span style="font-size: 12px">阅读时长≈1分钟</span></i>
            </div>
            <!--            首图 695 435 -->
            <div style="padding: 21px 0 21px 0;display: flex;justify-content: center;border-bottom: 1px solid #d4d4d5;border-top: 1px solid #d4d4d5;align-items: center;margin-top: 35px">
                <div class="picture" :style="
     {backgroundImage:'url('+blog.firstPicture+')'}" style="width: 65%;height: 435px;">

                </div>
            </div>

            <!--            文章-->
            <div style="margin-top: 210px"><p v-html="blog.content">
            </p></div>

            <!--            点赞按钮-->
            <div>
                <div style="margin-top: 50px;display: flex;justify-content: center">
                    <span @click="addThumbs" class="dianzan"
                          style="width: 59px;height: 43px;background-color: #409EFF;text-align: center;line-height: 43px;border-radius: 10px;cursor: pointer">
                        <i style="font-size: 30px" class="iconfont icon-dianzan"></i>
                    </span>
                    <span style="text-align: center;line-height: 43px;margin-left: 10px;color: #757575">{{blog.thumbs}}</span>
                    <!--            收藏按钮-->
                    <div style="margin-left: 10px;text-align: center;line-height: 50px;border-radius: 10px;cursor: pointer">


                        <i @click="collection" class="el-icon-star-on" :class="[collectionFlag===true?'color':'']"
                           style="font-size: 28px"></i>

                    </div>
                    <span style="margin-bottom: 8px;text-align: center;line-height: 42px;margin-left: 10px;color: #757575">{{collectionCount}}</span>

                    <!--            收藏按钮-->
                </div>
            </div>
            <!--            点赞按钮-->

            <!--            <div></div>-->
            <!--            分类-->
            <div style="margin-top: 50px;height: 70px;line-height: 70px;border-top: 1px solid #E6E6E6">
                <el-tag>{{blog.typeName}}</el-tag>
            </div>
            <!--            自我介绍-->
            <div id="input" style="height: 137px;background-color: #FCFFF5;border: 1px solid #eeeeee">
                <ul style="font-size: 13px;padding: 30px 0  0 21px;color: #2c662d">
                    <li>作者：{{blog.nickname}}</li>
                    <li>发表时间：{{blog.formatCreate}}</li>
                    <li>最后修改：{{blog.formatUpdate}}</li>
                    <li>本网站采用BY-NC-SA协议进行授权|版权所有，违者必究|如未注明，均为原创|转载：转载请注明原文链接</li>
                </ul>
            </div>
            <!--                发表评论模块-->
            <div style="margin-top: 20px">
                <el-form :model="formComment" :rules="rules" ref="formRef" class="demo-ruleForm">
                    <el-form-item prop="content">
                        <el-input maxlength="200"
                                  show-word-limit type="textarea" placeholder="友善评论"
                                  v-model="formComment.content"></el-input>
                    </el-form-item>
                    <span style="color: #919191;font-size: 14px" v-if="zisuflag">   剩余{{zishu}} 字
                    </span>
                    <span style="color: #919191;font-size: 14px" v-if="zishuflag02"> 超过 {{zishu02}}字</span>

                    <el-button style="margin-left: 15px" type="primary" @click="submitComment('formRef')">发表评论
                    </el-button>
                    <el-button type="success" v-if="flag===true" @click="clearAddParent">取消回复</el-button>

                </el-form>
            </div>
            <!--                发表评论模块-->

            <!--                评论回复模块-->
            <div style="margin-top: 20px">
                <!--                        顶部-->
                <div style="border-bottom: 1px solid #eee;font-size: 18px;font-weight: 400;padding-bottom: 5px"
                     class="header">Comments | {{count}} 条评论
                </div>
                <!--                   一个评论-->
                <div class="comment" v-for="(item,index) in commentList" style="">
                    <!--                   父 评论    -->
                    <div :class="[item.commentLevel===1?'level1':'level2']" style="">
                        <div class="content" style="display: flex">
                            <el-image
                                    style="width: 40px; height: 40px;border-radius: 20px"
                                    :src="item.avatar"
                                    :preview-src-list="[item.avatar]"
                            ></el-image>
                            <div class="right" style="display: flex;flex-direction: column;margin-left: 10px">
                                <div>
                                    <a href="#" style="text-decoration: none"><span
                                            style="font-size: 16px;color: #303133;font-weight: 400">{{item.userName}}</span></a>
                                    <span style="margin-left: 5px;font-size: 14px;font-weight: 400;color: #9999AD">{{item.formatTime}}</span>
                                    <el-tag style="margin-left: 5px" type="mini" effect="dark"
                                            @click="addParent(item.id,item.userId,item.userName)">回复
                                    </el-tag>
                                    <el-tag v-if="item.deleteflag===1" style="margin-left: 5px" size="mini"
                                            type="danger" effect="dark"
                                            @click="deleteComment(item.id)">删除
                                    </el-tag>
                                    <!--                                    应该传评论的id-->

                                </div>
                                <p v-html="item.content" style="margin-top: 5px"></p>

                            </div>
                        </div>
                    </div>

                </div>
                <!--                        一个评论-->


            </div>
            <!--                评论回复模块结束-->
        </el-card>
    </div>
</template>

<script>
    import  iconfont from '/src/assets/css/iconfont.css'
    import 'highlight.js/styles/monokai-sublime.css'
    import jwtDecode from 'jwt-decode'
    // import Global from "../assets/js/Global";
    import hljs from 'highlight.js'
    import Global from "../../public/static/Global";

    export default {
        watch: {
            'formComment.content': function f1(newval, oldval) {
                // console.log(newval)
                // console.log(oldval)
                // console.log(newval.length)
                // console.log(oldval.length)
                // 如果不是提交之后清除走这里
                if (newval == '') {  // 提交后清除走这里
                    this.zishu = 20;
                } else if (!newval == '') {  // 如果不是提交之后清除走这里
                    this.zisuflag = true;
                    this.zishu = this.zishu - (newval.length - oldval.length);
                } else if (oldval.length - newval.length > 0) {  // 说明是删除操作
                    this.zishu = this.zishu - (newval.length - oldval.length);
                }
                if (this.zishu < 0) {
                    this.zisuflag = false;

                    this.zishu = 0;
                    this.zishuflag02 = true
                    this.zishu02 = this.zishu02 - (newval.length - oldval.length);
                    this.$message.error('最多输入20个字');
                }
            }


        },
        name: "Detail",
        methods: {
            async getBlogDetail(id) {  // 得到博客的详情数据
                const {data: res} = await this.$http.get('/blog/detail/' + id)

                const token = localStorage.getItem('token')
                let userId
                if (token) {   // 如果有登录才解析，要不然会报错
                    const obj = jwtDecode(token)
                    userId = obj.id;
                }


                let blogId = this.$route.query.id  // 博客的id
                if (userId) {  // 如果用户的id不为空才走这，也就是你没登录也就没必要查看收藏状态
                    const {data: res1} = await this.$http.get('/collection/' + blogId + '/' + userId)// 通过博客id和用户id查出收藏状态
                    if (res1.data === 1) {
                        this.collectionFlag = true;
                    } else if (res.data === 0) {
                        this.collectionFlag = false;

                    }
                }

                // console.log(res.data);
                this.collectionCount = res.data.collection;
                res.data.firstPicture = Global.baseUrl + res.data.firstPicture;
                this.blog = res.data
            },

            async submitComment(formRef) { // 提交评论
                // 发表评论后清除实时数据
                this.zishu = 20;
                this.zishu02 = 0;
                this.zishuflag02 = false;
                this.zisuflag = false;

                const token = localStorage.getItem('token')
                if (!token) {
                    this.$message.error('请先登录');
                    return;
                }
                const obj = jwtDecode(token)
                this.zishu = this.formComment.content; // 进行字数的统计
                this.formComment.userName = obj.nickname;
                this.formComment.userId = obj.id;
                this.formComment.blogId = this.$route.query.id  // 博客的id
                this.formComment.blogTitle = this.blog.title  // 父级信息通过回复按钮在其他方法添加
                // console.log(obj)  // 如果是一级评论就不需要设计父级，由后端判断是否有父级插入一级
                let _this = this
                this.$refs[formRef].validate(async (valid) => { // 前端校验
                        if (valid) {
                            const {data: res} = await this.$http.post('comment', this.formComment)
                            // console.log(res);
                            if (res.meta.status === 200) {
                                this.$message({
                                    type: 'success',
                                    message: '评论成功'
                                })
                                _this.getCommentInfo() // 刷新评论
                                _this.getCommentCount() // 刷新评论个数
                                // this.$router.go(0)
                            } else {
                                this.$message({
                                    type: 'error',
                                    message: res.meta.msg
                                })
                            }

                        } else {
                            this.$message({
                                type: 'error',
                                message: '请检查！'
                            })
                            return false;
                        }
                    }
                );
                this.zishu = 20;
                this.zishu02 = 0;
                this.zishuflag02 = false;
                this.zisuflag = false;

                this.$refs[formRef].resetFields();


                // console.log(res);
            },
            async getCommentInfo() {  // 获取评论的信息
                const token = localStorage.getItem('token')
                let loginUserId
                let obj
                if (token) {  // 登录了才解析
                    obj = jwtDecode(token)

                    loginUserId = obj.id;  // 当前登录的用户id
                }

                let blogId = this.$route.query.id  // 博客的id
                const {data: res} = await this.$http.get('/comment/' + this.$route.query.id)// 通过博客id查询对应的评论
                let avatarImg;

                for (let i = 0; i < res.data.length; i++) {  // 取出对应评论的用户id，去查用户的头像
                    if (res.data[i].userId === loginUserId) {
                        res.data[i]['deleteflag'] = 1;  // 显示删除按钮
                    }
                    const {data: res1} = await this.$http.get('/comment/avatar/' + res.data[i].userId)
                    res.data[i]['avatar'] = Global.baseUrl + res1.data; // push commentList数组
                    // this.getAvatarByUserId();
                    // console.log(res1.data);
                }
                this.commentList = res.data
                // console.log(this.commentList)

                console.log(res);
            },
            getAvatarByUserId(id) { // 通过用户获取头像
                // console.log(res.data.data)

                // let img=    res.data
                // console.log(res)
                // return 1;
            },
            addParent(parentCommentId, parentCommentUserId, userName) {  // 回复评论，添加父级信息
                // console.log(parentCommentId)
                // console.log(parentCommentUserId);
                // console.log(userName);
                this.flag = true;
                this.$message.success('回复' + userName + '请转至输入框');
                // this.formComment.content = '@' + userName + ':';
                this.formComment.parentCommentId = parentCommentId;
                this.formComment.parentCommentUserId = parentCommentUserId;
                this.formComment.userName = userName;
            },
            clearAddParent() {  // 清除父级信息
                this.flag = false;
                this.$message.error('取消了回复')
                this.formComment.parentCommentId = null
                this.formComment.parentCommentUserId = null
                this.formComment.userName = null;
            },
            async getCommentCount() {  // 得到评论数量
                // this.$message.
                const {data: res} = await this.$http.get('/comment/count/' + this.$route.query.id)// 通过博客id查询对应的评论总数
                // console.log(res)
                this.count = res.data
            },
            async addThumbs() {  // 点赞
                const token = localStorage.getItem('token')
                if (!token) {  // 未登录
                    this.$message.error('请先登录，再点赞');
                    return;
                }
                const obj = jwtDecode(token)
                let userId = obj.id;
                let blogId = this.$route.query.id  // 博客的id
                const {data: res} = await this.$http.post('/blog/detail/thumbs/' + blogId + '/' + userId)// 通过博客id查询对应的评论总数
                // console.log(res)
                if (res.meta.status === 200) {
                    this.$message.success('点赞成功')
                    this.blog.thumbs++
                } else {
                    this.$message.error(res.meta.msg);
                }
            },
            async collection() { // 收藏
                const token = localStorage.getItem('token')
                if (!token) {  // 未登录
                    this.$message.error('请先登录，再收藏');
                    return;
                }
                const obj = jwtDecode(token)
                let userId = obj.id;
                let blogId = this.$route.query.id  // 博客的id
                const {data: res} = await this.$http.post('/collection/' + blogId + '/' + userId)// 通过博客id插入
                // console.log(res)
                if (res.data === 1) {  // 收藏成功
                    this.$message.success('收藏成功');
                    this.collectionFlag = true// 显示蓝色
                    this.collectionCount++
                } else if (res.data === 0) {   // 取消收藏
                    this.collectionCount--
                    this.collectionFlag = false// 不显示蓝色

                    this.$message.warning('取消收藏成功');
                } else if (res.data === -1) {
                    this.$message.error('收藏失败')
                }
                // this.$message.success('22')
            },
            async deleteComment(id) { // 前台删除评论
                const token = localStorage.getItem('token')
                const obj = jwtDecode(token)
                let blogId = this.$route.query.id  // 博客的id

                let loginUserId = obj.id;  // 登录的用户id
                const {data: res} = await this.$http.delete('/comment/' + id + '/' + loginUserId)// 通过博客id插入
                if (res.meta.status === 200) {
                    this.$message.success('删除评论成功')
                    this.getCommentInfo();
                } else {
                    this.$message.error('删除评论失败')

                }

            }
        },
        data() {
            return {
                deleteFlag: false,
                collectionFlag: false,  // 收藏的效果
                collectionCount: 0, // 收藏数
                zishuflag02: false, // 超过,
                zishu02: 0,
                zisuflag: false,
                zishu: 20,
                flag: false, // 表示添加 父级信息时候的 取消回复组件
                temp: ""  // 占时存储头像
                ,
                form: {   // 评论模块
                    content: ''
                },
                blog: {

                    thumbs: 0 // 点赞数默认为0
                },  // 博客详情数据
                formComment: {  // 评论表单
                    userName: "",
                    userId: "",
                    blogId: "",
                    blogTitle: "",
                    content: "",
                    commentLevel: "",
                    parentCommentId: "",
                    parentCommentUserId: ""
                }, // 评论表单
                commentList: [],  // 评论集合
                count: 0,// 评论总数
                rules: {
                    content: [
                        {required: true, message: '请输入评论', trigger: 'blur'},
                        {min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur'}
                    ],
                }
            }
        },
        created() {
            // console.log(this.$route.query.id);
            this.getBlogDetail(this.$route.query.id)
            this.getCommentInfo();
            this.getCommentCount();
        },
        Destroyed() {
            this.commentList = [];
        },

    }
</script>

<style lang="less" scoped>
    .picture {
        /*margin-top: 35px;*/
        /*background-color: ;*/
        /*background-image: url("https://api.dujin.org/bing/1920.php");*/
        background-repeat: no-repeat;
        /*background-repeat: ;*/
        background-size: 100% 100%;
        /*border-top: 1px solid #666666;*/
        /*border-bottom: 1px solid #666666;*/
    }

    /*@font-face {*/
    /*    font-family: "iconfont"; !* Project id 2847628 *!*/
    /*    src: url('//at.alicdn.com/t/font_2847628_4wrrs5jrjjq.woff2?t=1633189597417') format('woff2'),*/
    /*    url('//at.alicdn.com/t/font_2847628_4wrrs5jrjjq.woff?t=1633189597417') format('woff'),*/
    /*    url('//at.alicdn.com/t/font_2847628_4wrrs5jrjjq.ttf?t=1633189597417') format('truetype');*/
    /*}*/

    /*.iconfont {*/
    /*    font-family: "iconfont" !important;*/
    /*    font-size: 16px;*/
    /*    font-style: normal;*/
    /*    -webkit-font-smoothing: antialiased;*/
    /*    -moz-osx-font-smoothing: grayscale;*/
    /*}*/

    /*.icon-dianzan:before {*/
    /*    content: "\e600";*/
    /*}*/

    .level1 {
        margin-left: 10px;
        margin-top: 11px
    }

    .level2 {
        margin: 35px 0 5px 35px
    }

    .dianzan {

    }

    .title {
        transition: all 0.4s;
        font-family: 'PingFang SC', 'Microsoft YaHei', 'SimHei', 'Arial', 'SimSun';
    }

    .title:hover {
        /*transition: ;*/
        transform: scale(1.3);
    }

    .dianzan:hover {
        /*background-color: #66B1FF;*/
        background-color: #66B1FF !important;
    }

    .color {
        /*background-color: ;*/
        color: #00A1D6;
    }
</style>